﻿using BigDogSoft.Utils;
using HslCommunication;
using HslCommunication.Core.Net;
using Infrastructure.DAL;
using Infrastructure.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BigDogSoft.Pages.forms
{
    public partial class FrmFormulaAdd : Form
    {
        public EventHandler SaveSuccessEvent { get; set; }
        private List<FormulaTplParam> list = null;
        private FormulaTpl currentTpl = null;
        private Formula editObj = null;
        private int lastY = 0;
        public FrmFormulaAdd(FormulaTpl tpl)
        {
            InitializeComponent();
            this.currentTpl = tpl;
            this.lblTplName.Text = tpl.template_name;
            //查询模板下的参数列表
            list = FormulaDAL.GetFormulaTplParamsBy(tpl.id);
            Point locat= this.txtFormulaName.Location; //拿到配方名称输入框的定位
            lastY = locat.Y + this.txtFormulaName.Height + 5;
            this.Height += list.Count * 33;
            foreach (var item in list)
            {
                DynmicCreateInputControl(item);
            }
            this.btnSetting.Enabled = false;
        }

        public FrmFormulaAdd(FormulaTpl tpl,Formula obj) : this(tpl)
        {
            this.Text = "配方-编辑";
            this.txtFormulaName.Text = obj.formula_name;
            editObj = obj;
            foreach (Control control in Controls)
            {
                if(control is TextBox && control.Name.StartsWith("p"))
                {
                    switch (control.Name)
                    {
                        case "p1": control.Text=obj.p1; break;
                        case "p2": control.Text = obj.p2; break;
                        case "p3": control.Text = obj.p3; break;
                        case "p4": control.Text = obj.p4 ; break;
                        case "p5": control.Text = obj.p5 ; break;
                        case "p6": control.Text = obj.p6 ; break;
                        case "p7": control.Text = obj.p7 ; break;
                        case "p8": control.Text = obj.p8 ; break;
                        case "p9": control.Text = obj.p9 ; break;
                        case "p10": control.Text = obj.p10 ; break;
                        case "p11": control.Text = obj.p11 ; break;
                        case "p12": control.Text = obj.p12 ; break;
                        case "p13": control.Text = obj.p13 ; break;
                        case "p14": control.Text = obj.p14 ; break;
                        case "p15": control.Text = obj.p15 ; break;
                        case "p16": control.Text = obj.p16 ; break;
                        case "p17": control.Text = obj.p17 ; break;
                        case "p18": control.Text = obj.p18 ; break;
                        case "p19": control.Text = obj.p19; break;
                        case "p20": control.Text = obj.p20 ; break;
                        case "p21": control.Text = obj.p21; break;
                        case "p22": control.Text = obj.p22 ; break;
                        case "p23": control.Text = obj.p23; break;
                        case "p24": control.Text = obj.p24; break;
                        case "p25": control.Text = obj.p25; break;
                        default:
                            break;
                    }
                }
            }
            this.btnSetting.Enabled = true;
        }

        private void DynmicCreateInputControl(FormulaTplParam item)
        {
           
            Label lbl = new Label();
            lbl.Text = item.param_name;
            lbl.Location = new Point(30, lastY+5);
            TextBox txt = new TextBox();
            txt.Width = 200;
            txt.Name = item.param_field;
            txt.Location = new Point(30 + lbl.Width + 10,lastY);
            this.Controls.Add(lbl);
            this.Controls.Add(txt);
            lastY = txt.Location.Y+txt.Height+5;
        }

        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt2_BtnClick(object sender, EventArgs e)
        {
            Formula obj = new Formula();
            obj.id =editObj==null?0:editObj.id;
            obj.formula_tpl_id = currentTpl.id;
            obj.formula_name = this.txtFormulaName.Text.Trim();
            obj.create_time = DateTime.Now;
            obj.update_time = DateTime.Now;
            obj.create_user = SessionContext.CurrentUser.account;
            obj.update_user = SessionContext.CurrentUser.account;

            foreach (Control item in this.Controls)
            {
                if(item is TextBox && item.Name.StartsWith("p"))
                {
                    //动态字段
                    string val = item.Text.Trim();
                    
                    switch (item.Name)
                    {
                        case "p1":obj.p1 = val;break;
                        case "p2":obj.p2 = val;break;
                        case "p3": obj.p3 = val; break;
                        case "p4": obj.p4 = val; break;
                        case "p5": obj.p5 = val; break;
                        case "p6": obj.p6 = val; break;
                        case "p7": obj.p7 = val; break;
                        case "p8": obj.p8 = val; break;
                        case "p9": obj.p9 = val; break;
                        case "p10": obj.p10 = val; break;
                        case "p11": obj.p11 = val; break;
                        case "p12": obj.p12 = val; break;
                        case "p13": obj.p13 = val; break;
                        case "p14": obj.p14 = val; break;
                        case "p15": obj.p15 = val; break;
                        case "p16": obj.p16 = val; break;
                        case "p17": obj.p17 = val; break;
                        case "p18": obj.p18 = val; break;
                        case "p19": obj.p19 = val; break;
                        case "p20": obj.p20 = val; break;
                        case "p21": obj.p21 = val; break;
                        case "p22": obj.p22 = val; break;
                        case "p23": obj.p23 = val; break;
                        case "p24": obj.p24 = val; break;
                        case "p25": obj.p25 = val; break;
                        default:
                            break;
                    }
                }
            }
            int rows= FormulaDAL.SaveFormula(obj);
            if (rows <= 0)
            {
                MessageBox.Show("保存失败！");
            }
            else
            {
                if (SaveSuccessEvent != null)
                {
                    SaveSuccessEvent(currentTpl, e);
                }
            }
        }
        private string GetModelValue(string FieldName, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object o = Ts.GetProperty(FieldName).GetValue(obj, null);
                string Value = Convert.ToString(o);
                if (string.IsNullOrEmpty(Value)) return null;
                return Value;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 投料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt4_BtnClick(object sender, EventArgs e)
        {
            if (editObj != null)
            {
                Device device=DeviceVarDAL.GetDeviceBy(currentTpl.device_id);
                List<FormulaTplParam> paramList= FormulaDAL.GetFormulaTplParamsBy(currentTpl.id);

                //写数据
                NetworkDeviceBase netClient = DeviceComminucationFactory.GetDeviceNetClient(device);
                if (netClient != null)
                {
                    foreach (var par in paramList)
                    {
                        OperateResult result = null;
                        string val = string.Empty;
                        VarType vt;
                        Enum.TryParse<VarType>(par.param_type, out vt);
                        switch (vt)
                        {
                            case VarType.Boolean:
                                val = GetModelValue(par.param_field, editObj);
                                bool b = Convert.ToBoolean(val);
                                result= netClient.Write(par.param_address, b);
                                if (!string.IsNullOrEmpty(par.verify_address))
                                {
                                    //读取数据比对
                                   OperateResult<bool> br=  netClient.ReadBool(par.verify_address);
                                    if (!br.IsSuccess || br.Content != b)
                                    {
                                        MessageBox.Show("参数："+par.param_name+"写入错误！");
                                        return;
                                    }
                                }
                                break;
                            case VarType.Float:
                                 val = GetModelValue(par.param_field, editObj);
                                float f = Convert.ToSingle(val);
                                result = netClient.Write(par.param_address, f);
                                if (!string.IsNullOrEmpty(par.verify_address))
                                {
                                    //读取数据比对
                                    OperateResult<float> br = netClient.ReadFloat(par.verify_address);
                                    if (!br.IsSuccess || br.Content != f)
                                    {
                                        MessageBox.Show("参数：" + par.param_name + "写入错误！");
                                        return;
                                    }
                                }
                                break;
                            case VarType.Int16:
                                 val = GetModelValue(par.param_field, editObj);
                                Int16 i16 = Convert.ToInt16(val);
                                result = netClient.Write(par.param_address, i16);
                                break;
                            case VarType.Int32:
                                 val = GetModelValue(par.param_field, editObj);
                                Int32 i32 = Convert.ToInt32(val);
                                result = netClient.Write(par.param_address, i32);
                                break;
                            case VarType.UInt16:
                                 val = GetModelValue(par.param_field, editObj);
                                UInt16 ui16 = Convert.ToUInt16(val);
                                result = netClient.Write(par.param_address, ui16);
                                break;
                            case VarType.UInt32:
                                 val = GetModelValue(par.param_field, editObj);
                                UInt32 ui32 = Convert.ToUInt32(val);
                                result = netClient.Write(par.param_address, ui32);
                                break;
                        }
                        if (!result.IsSuccess)
                        {
                            MessageBox.Show("写入数据发生错误："+result.ErrorCode);
                            return;
                        }
                    }
                    MessageBox.Show("投料成功！");
                }
                else
                {
                    MessageBox.Show("初始化设备连接出错！请查看日志");
                }
            }
        }
    }
}
